{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Multi-Line Tooltip\n",
    "==================\n",
    "This example shows how you can use selections and layers to create a multi-line tooltip\n",
    "that tracks the x position of the cursor.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# category: interactive\n",
    "\n",
    "import altair as alt\n",
    "alt.data_transformers.enable('json')\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "np.random.seed(42)\n",
    "data = pd.DataFrame(np.cumsum(np.random.randn(100, 3), 0).round(2),\n",
    "                    columns=['A', 'B', 'C'], index=pd.RangeIndex(100, name='x'))\n",
    "data = data.reset_index().melt('x', var_name='category', value_name='y')\n",
    "\n",
    "# Create a selection that chooses the nearest point & selects based on x-value\n",
    "nearest = alt.selection(type='single', nearest=True, on='mouseover',\n",
    "                        fields=['x'], empty='none')\n",
    "\n",
    "# The basic line\n",
    "line = alt.Chart().mark_line(interpolate='basis').encode(\n",
    "    x='x:Q',\n",
    "    y='y:Q',\n",
    "    color='category:N'\n",
    ")\n",
    "\n",
    "# Transparent selectors across the chart. This is what tells us\n",
    "# the x-value of the cursor\n",
    "selectors = alt.Chart().mark_point().encode(\n",
    "    x='x:Q',\n",
    "    opacity=alt.value(0),\n",
    ").properties(\n",
    "    selection=nearest\n",
    ")\n",
    "\n",
    "# Draw points on the line, and highlight based on selection\n",
    "points = line.mark_point().encode(\n",
    "    opacity=alt.condition(nearest, alt.value(1), alt.value(0))\n",
    ")\n",
    "\n",
    "# Draw text labels near the points, and highlight based on selection\n",
    "text = line.mark_text(align='left', dx=5, dy=-5).encode(\n",
    "    text=alt.condition(nearest, 'y:Q', alt.value(' '))\n",
    ")\n",
    "\n",
    "# Draw a rule at the location of the selection\n",
    "rules = alt.Chart().mark_rule(color='gray').encode(\n",
    "    x='x:Q',\n",
    ").transform_filter(\n",
    "    nearest.ref()\n",
    ")\n",
    "\n",
    "# Put the five layers into a chart and bind the data\n",
    "alt.layer(line, selectors, points, rules, text,\n",
    "          data=data, width=600, height=300)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "env": {},
   "interrupt_mode": "signal",
   "language": "python",
   "metadata": {},
   "name": "python3"
  },
  "language": "python"
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
